<template>
  <el-row :gutter="10">
    <el-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
      <OrderAfterSaleInfo :order-data="orderData">
        <template #tool>
          <div class="w-full flex h-32px items-center justify-end">
            <el-button v-if="orderData.status === 10" type="primary" @click="agree"
              >同意售后</el-button
            >
            <el-button v-if="orderData.status === 10" type="primary" @click="disagree">
              拒绝售后
            </el-button>
            <el-button v-if="orderData.status === 30" type="primary" @click="receive">
              确认收货
            </el-button>
            <el-button v-if="orderData.status === 30" type="primary" @click="refuse"
              >拒绝收货</el-button
            >
            <el-button v-if="orderData.status === 40" type="primary" @click="refund"
              >确认退款</el-button
            >
          </div>
        </template>
      </OrderAfterSaleInfo>
    </el-col>
    <el-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
      <ContentWrap :title="'订单信息'" :body-style="{ padding: 0 }" class="!mb-0px !border-b-none">
        <template #header>
          <div class="flex items-center justify-end w-full">
            <div>
              <el-text class="mr-5px! custom-text-14! font-bold">
                订单号: {{ orderData.no }}
              </el-text>
              <el-button @click.stop="copyContent(orderData.no)" link>
                <Icon icon="ep:copy-document" :size="16" class="color-[var(--el-color-primary)]" />
              </el-button>
              <el-text class="mr-5px! custom-text-14! font-bold">
                下单时间: {{ formatDate(orderData.createTime!) }}
              </el-text>
              <el-text class="mr-5px! custom-text-14! font-bold">
                订单状态:
                <dict-tag
                  class="ml-5px"
                  :type="DICT_TYPE.TRADE_ORDER_STATUS"
                  :value="orderData.status!"
                />
              </el-text>
            </div>
          </div>
        </template>
      </ContentWrap>
    </el-col>
    <el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
      <!-- 订单信息 -->
      <OrderBasicInfo :order-data="orderData">
        <template #tool>
          <div class="flex justify-end w-full">
            <!-- <el-button>打印小票 </el-button>
            <el-button>电子合同 </el-button> -->
          </div>
        </template>
      </OrderBasicInfo>
    </el-col>
    <el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
      <!-- 会员信息 -->
      <OrderMemberInfo :order-data="orderData">
        <template #tool>
          <div class="w-full flex h-32px items-center justify-end">
            <Icon icon="ep:shop" :size="16" />
          </div>
        </template>
      </OrderMemberInfo>
    </el-col>
  </el-row>
  <!-- 商品信息 -->

  <OrderGoodsInfo :goods-list="[orderData.orderItem]">
    <template #extension>
      <el-table-column align="center" label="退款金额" prop="payPrice">
        <template #default="{ row }">{{ fenToYuan(row.payPrice) }}元</template>
      </el-table-column>
    </template>
  </OrderGoodsInfo>
  <ContentWrap class="!mb-10px">
    <!-- 操作日志 -->
    <el-descriptions title="售后日志">
      <el-descriptions-item labelClassName="no-colon">
        <el-timeline>
          <el-timeline-item
            v-for="saleLog in orderData.logs"
            :key="saleLog.id"
            :timestamp="formatDate(saleLog.createTime)"
            placement="top"
          >
            <div :class="[isDark ? 'el-timeline-right-content-dark' : 'el-timeline-right-content']">
              <span>{{ saleLog.content }}</span>
            </div>
            <template #dot>
              <span
                :style="{ backgroundColor: getUserTypeColor(saleLog.userType) }"
                class="dot-node-style"
              >
                {{ getDictLabel(DICT_TYPE.USER_TYPE, saleLog.userType)[0] || '系' }}
              </span>
            </template>
          </el-timeline-item>
        </el-timeline>
      </el-descriptions-item>
    </el-descriptions>
  </ContentWrap>

  <!-- 各种操作的弹窗 -->
  <UpdateAuditReasonForm ref="updateAuditReasonFormRef" @success="getDetail" />
</template>
<script lang="ts" setup>
import * as AfterSaleApi from '@/api/mall/trade/afterSale/index'
import { fenToYuan } from '@/utils'
import { DICT_TYPE, getDictLabel, getDictObj } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'
import UpdateAuditReasonForm from '@/views/mall/trade/afterSale/form/AfterSaleDisagreeForm.vue'

import { useTagsViewStore } from '@/store/modules/tagsView'
import {
  OrderBasicInfo,
  OrderMemberInfo,
  OrderAfterSaleInfo,
  OrderGoodsInfo
} from '@/views/mall/trade/order/components'
import { useAppStore } from '@/store/modules/app'

const appStore = useAppStore()

const isDark = computed(() => appStore.getIsDark)
defineOptions({ name: 'TradeAfterSaleDetail' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { params } = useRoute() // 查询参数
const { push, currentRoute } = useRouter() // 路由
const orderData = ref({
  order: {},
  logs: [],
  status: undefined,
  orderItem: {}
})
const updateAuditReasonFormRef = ref() // 拒绝售后表单 Ref

/** 获得 userType 颜色 */
const getUserTypeColor = (type: number) => {
  const dict = getDictObj(DICT_TYPE.USER_TYPE, type)
  switch (dict?.colorType) {
    case 'success':
      return '#67C23A'
    case 'info':
      return '#909399'
    case 'warning':
      return '#E6A23C'
    case 'danger':
      return '#F56C6C'
  }
  return '#165DFF'
}

/** 获得详情 */
const getDetail = async () => {
  const id = params.id as unknown as number
  if (id) {
    const res = await AfterSaleApi.getAfterSale(id)
    // 没有表单信息则关闭页面返回
    if (res == null) {
      message.notifyError('售后订单不存在')
      close()
    }
    orderData.value = res
  }
}

/** 同意售后 */
const agree = async () => {
  try {
    // 二次确认
    await message.confirm('是否同意售后？')
    await AfterSaleApi.agree(orderData.value.id)
    // 提示成功
    message.success(t('common.success'))
    await getDetail()
  } catch {}
}

/** 拒绝售后 */
const disagree = async () => {
  updateAuditReasonFormRef.value?.open(orderData.value)
}

/** 确认收货 */
const receive = async () => {
  try {
    // 二次确认
    await message.confirm('是否确认收货？')
    await AfterSaleApi.receive(orderData.value.id)
    // 提示成功
    message.success(t('common.success'))
    await getDetail()
  } catch {}
}

/** 拒绝收货 */
const refuse = async () => {
  try {
    // 二次确认
    await message.confirm('是否拒绝收货？')
    await AfterSaleApi.refuse(orderData.value.id)
    // 提示成功
    message.success(t('common.success'))
    await getDetail()
  } catch {}
}

/** 确认退款 */
const refund = async () => {
  try {
    // 二次确认
    await message.confirm('是否确认退款？')
    await AfterSaleApi.refund(orderData.value.id)
    // 提示成功
    message.success(t('common.success'))
    await getDetail()
  } catch {}
}

const { delView } = useTagsViewStore() // 视图操作
/** 关闭 tag */
const close = () => {
  delView(unref(currentRoute))
  push({ name: 'TradeAfterSale' })
}
onMounted(async () => {
  await getDetail()
})
</script>
<style lang="scss" scoped>
:deep(.el-descriptions) {
  &:not(:nth-child(1)) {
    margin-top: 20px;
  }

  .el-descriptions__title {
    display: flex;
    align-items: center;
  }

  .el-descriptions-item__container {
    margin: 0 10px;

    .no-colon {
      margin: 0;

      &::after {
        content: '';
      }
    }
  }
}

// 时间线样式调整
:deep(.el-timeline) {
  margin: 10px 0 0 160px;

  .el-timeline-item__wrapper {
    position: relative;
    top: -20px;

    .el-timeline-item__timestamp {
      position: absolute !important;
      top: 10px;
      left: -150px;
    }
  }

  .el-timeline-right-content {
    display: flex;
    align-items: center;
    min-height: 30px;
    padding: 10px;
    background-color: var(--app-content-bg-color);

    &::before {
      position: absolute;
      top: 10px;
      left: 13px;
      border-color: transparent var(--app-content-bg-color) transparent transparent; /* 尖角颜色，左侧朝向 */
      border-style: solid;
      border-width: 8px; /* 调整尖角大小 */
      content: '';
    }
    &-dark {
      display: flex;
      align-items: center;
      min-height: 30px;
      padding: 10px;
      border-radius: var(--el-card-border-radius);
      background-color: var(--el-bg-color);

      &::before {
        position: absolute;
        top: 10px;
        left: 13px; /* 将伪元素水平居中 */
        border-color: transparent var(--el-bg-color) transparent transparent; /* 尖角颜色，左侧朝向 */
        border-style: solid;
        border-width: 8px; /* 调整尖角大小 */
        content: ''; /* 必须设置 content 属性 */
      }
    }
  }

  .dot-node-style {
    position: absolute;
    left: -5px;
    display: flex;
    width: 20px;
    height: 20px;
    font-size: 10px;
    color: #fff;
    border-radius: 50%;
    justify-content: center;
    align-items: center;
  }
}
</style>
